﻿using System;
using System.Collections.Generic;
using System.Linq;
using BookLibrary.Domain.Book;
using BookLibrary.Domain.BorrowedProcess;
using BookLibrary.DomainService.Contracts;
using BookLibrary.Repository.Contracts;

namespace BookLibrary.DomainService.Implements
{
    public class BooLibraryProcessDomainService:IBookLibraryProcessDomainService
    {
        private readonly IBookLibraryProcessRepository _bookLibraryProcessRepository;
        private readonly IBookRepository _bookRepository;

        public BooLibraryProcessDomainService(IBookLibraryProcessRepository bookLibraryProcessRepository,
            IBookRepository bookRepository)
        {
            _bookLibraryProcessRepository = bookLibraryProcessRepository;
            _bookRepository = bookRepository;
        }

        public BookLibraryProcess GetBookLibraryProcess(Guid bookLibraryProcessId)
        {
            var borrowedProcess = _bookLibraryProcessRepository.Find(x => x.Id == bookLibraryProcessId).FirstOrDefault();

            return borrowedProcess;
        }

        public void BorrowBooks(Guid bookLibraryProcessId, Guid bookId, TimeSpan borrowedInterval)
        {
            var bookLibraryProcess = GetBookLibraryProcess(bookLibraryProcessId);
            BorrowBook(bookLibraryProcess, bookId, borrowedInterval);
        }

        public void BorrowBooksOnFirstTime(Guid userId, Guid bookId, TimeSpan borrowedInterval)
        {
            var borrowedProcess = BookLibraryProcess.StartNewProcess(userId);
            BorrowBook(borrowedProcess, bookId, borrowedInterval);
        }

        private void BorrowBook(BookLibraryProcess bookLibraryProcess, Guid bookId, TimeSpan borrowedInterval)
        {
            var book = _bookRepository.Get(bookId);
            book.Borrow();
            _bookRepository.Update(book);

            bookLibraryProcess.BorrowBook(book, borrowedInterval);
            _bookLibraryProcessRepository.Add(bookLibraryProcess);
        }

        public void ReturnBook(Guid bookLibraryProcessId, Guid bookId)
        {
            var bookBorrowedProcess = GetBookLibraryProcess(bookLibraryProcessId);
            var book = _bookRepository.Get(bookId);
            book.Return();
            _bookRepository.Update(book);

            bookBorrowedProcess.ReturnBook(book);
            _bookLibraryProcessRepository.Update(bookBorrowedProcess);
        }
    }
}